<?php
require_once( 'tsAuth.class.php' );
require_once( 'tsConfig.class.php' );
require_once( 'facebook/facebook.php' );

/**
 * authorize for facebook
 *
 * @author K.Tamura <tamura@terras.co.jp>
 */
class tsAuth_facebook extends tsAuth
{

    public $config = array();

    public function __construct()
    {
        $_cfg = tsConfig::getInstance( CONF_FILE );

        // set facebook connect config
        //
        $config = array();
        $config['appId'] = $_cfg->get( 'FACEBOOK', 'appId' );
        $config['secret'] = $_cfg->get( 'FACEBOOK', 'secret' );
        $config['redirect_uri'] = $_cfg->get( 'FACEBOOK', 'redirect_uri' );
        $config['scope'] = $_cfg->get( 'FACEBOOK', 'scope' );

        $this->config = $config;
    }

    public function checkLogin()
    {
        // facebook crawler is exclusion of the authorize
        //
        if( false !== strpos( $_SERVER['HTTP_USER_AGENT'], 'facebookexternalhit' ) )
        {
            return ;
        }

        // generate Facebook SDK instance
        //
        $fbconfig = array(
                         'appId'  => $this->config['appId'],
                         'secret' => $this->config['secret'],
                         );
        $facebook = new Facebook( $fbconfig );

        // get facebook userid
        //
        $uid = $facebook->getUser();

        $islogin = true;
        if( $uid )
        {
            try
            {
                $permits = $facebook->api( '/me/permissions' );
                if( true === isset( $permits['data'][0] ) )
                {
                    $permits = array_keys( $permits['data'][0] );
                    $scopes = explode( ',', $this->config['scope'] );
                    foreach( $scopes as $scope )
                    {
                        $scope = trim( $scope );
                        if( true !== in_array( $scope, $permits ) )
                        {
                            $islogin = false;
                            break;
                        }
                    }
                }
            }
            catch( FacebookApiException $e )
            {
                $islogin = false;
            }
        }
        else
        {
            $islogin = false;
        }

        if( true !== $islogin )
        {
            $config = array();
            $config['scope'] = $this->config['scope'];
            $config['redirect_uri'] = $this->config['redirect_uri'];
            $config['display'] = 'page';
            $login_url = $facebook->getLoginUrl( $config );
            self::redirect( $login_url );
        }
    }

    private static function redirect( $url )
    {
    	echo "<script type='text/javascript'>";
        echo "window.top.location.href = '" . $url . "'";
        echo "</script>";
        exit;
    }

}
